#!/usr/bin/env ruby

# Copyright (c) 2021-2025 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

include_relative 'common.irt'
include_relative 'string_helpers.irt'

GenerateStringEqualsUnrolled(compressed=true)
GenerateStringEqualsUnrolled(compressed=false)
GenerateStringEquals(lang='', dynamic=false, compressed=true, :FastPath)
GenerateStringEquals(lang='', dynamic=false, compressed=true, :NativePlus)
GenerateStringEquals(lang='', dynamic=false, compressed=false, :FastPath)
GenerateCreateStringFromStringTlab(string_compression_enabled=true)
GenerateCreateStringFromStringTlab(string_compression_enabled=false)
GenerateCreateStringFromCharArrayTlab(string_compression_enabled=true)
GenerateCreateStringFromCharArrayTlab(string_compression_enabled=false)
GenerateCreateStringFromZeroBasedCharArrayTlab(string_compression_enabled=true)
GenerateCreateStringFromZeroBasedCharArrayTlab(string_compression_enabled=false)
GenerateSubstringFromStringTlab(string_compression_enabled=true)
GenerateSubstringFromStringTlab(string_compression_enabled=false)
GenerateStringGetCharsTlab(string_compression_enabled=true)
GenerateStringGetCharsTlab(string_compression_enabled=false)
GenerateStringHashCode(string_compression_enabled=true, :FastPath)
GenerateStringHashCode(string_compression_enabled=true, :NativePlus)
GenerateStringHashCode(string_compression_enabled=false, :FastPath)

def GenerateStringCompareTo(cgmode)
  suffix = (cgmode == :NativePlus ? 'NativePlus': '')
  function("StringCompareTo#{suffix}",
           params: {str1_orig: 'ref', str2_orig: 'ref'},
           regmap: $full_regmap,
           regalloc_set: $panda_mask,
           mode: [cgmode]) {

    # Arm32 is not supported
    if Options.arch == :arm32
      Intrinsic(:UNREACHABLE).void.Terminator
      next
    end

    str1 := try_use_cached_flat_str(str1_orig)
    str2 := try_use_cached_flat_str(str2_orig)

    Return(macroStringCompareTo(str1, str2)).i32

Label(:SlowPathEntrypoint)
    if cgmode == :NativePlus
        Return(Call(str1_orig, str2_orig).Method('CoreStringCompareTo').i32).i32
    else
      entrypoint = get_entrypoint_offset("STRING_COMPARE_TO_SLOW_PATH")
      Intrinsic(:SLOW_PATH_ENTRY, str1_orig, str2_orig).AddImm(entrypoint).MethodAsImm("StringCompareToUsualBridge").Terminator.i32
      Intrinsic(:UNREACHABLE).Terminator.void if defines.DEBUG
    end
  }
end

GenerateStringCompareTo(:FastPath)
GenerateStringCompareTo(:NativePlus)

include_plugin 'ets_string'
